<?php
/**
 * Laravel-Vue-Admin
 * @Author:技术铺
 * @Date:2021/11/22
 */

namespace App\Services;

use App\Models\InfoModel;
use App\Http\Resources\InfoModelCollection;

/**
 * 信息模型模块服务层
 *
 * Class InfoModelService
 * @package App\Services
 */
class InfoModelService
{

    /**
     * 获取所有模型
     * @return array|\Illuminate\Contracts\Support\Arrayable|\JsonSerializable|mixed
     */
    public static function getAllList()
    {
        $result = CacheService::getCache('infoModelService');
        if ($result == null) {
            $resource = InfoModel::where('status', 1)->get();
            $result = InfoModelCollection::make($resource)->toArray(null);
            CacheService::setCache('infoModelService', $result);
        }
        return $result ? $result['items'] : [];
    }


    /**
     * 根据模型标识获取模型信息
     * @param $id // 模型ID
     * @param $fields // 查询指定字段
     * @return array
     */
    public static function getModelById($id = 0, $fields = [])
    {
        if(!$id) return '';
        $getFirst = collect(self::getAllList())->firstWhere('id', $id);
        if($getFirst && $fields) {
            $newModel = [];
            foreach($fields as $value) {
                $newModel[$value] = $getFirst[$value];
            }
            $getFirst = $newModel;
        }
        return $getFirst ?: [];
    }

    /**
     * 根据模型标识获取模型名称
     * @param $id // 模型ID
     * @return string
     */
    public static function getModelNameById($id = 0)
    {
        if(!$id) return '';
        $getFirst = collect(self::getAllList())->firstWhere('id', $id);
        return $getFirst ? $getFirst['name'] : "";
    }

}
